package org.linuxsogood.boot.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author honway.liu
 * @date 2019-07-06 12:03
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
public class DistributionLockTest {
    public static void main(String[] args) throws Exception {
        // 创建zk客户端并连接到zk
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        String serverAddr = "127.0.0.1:2181";
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString(serverAddr).sessionTimeoutMs(3000).retryPolicy(retryPolicy)
                .namespace("workspace").build();
        // CuratorFramework client = CuratorFrameworkFactory.newClient(serverAddr, retryPolicy);
        client.start();

        // 分布式锁实现
        InterProcessMutex processMutex = new InterProcessMutex(client, "/curator/lock");
        // 获取锁
        processMutex.acquire();
        System.out.println("执行逻辑");
        // 释放锁
        processMutex.release();
        client.close();

    }

}
